#include "server.h"
#include "ui_server.h"

Server::Server(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Server)
{
    ui->setupUi(this);

//  init
    ui->cIP->setText("127.0.0.1");
    ui->cPort->setText("9999");
    ui->sPort->setText("8888");//我的端口

    udp1 = new QUdpSocket(this);

//    if want receive must bind port
//    QHostAddress::AnyIPv4组播时要指定绑定ipv4
    udp1->bind(QHostAddress::AnyIPv4,ui->sPort->text().toInt());

//    send msg
    connect(ui->send,&QPushButton::clicked,this,[=](){
//        QHostAddress::Broadcast == 255.255.255.255
        udp1->writeDatagram(ui->msg->toPlainText().toUtf8(),QHostAddress("224.0.0.10"),ui->cPort->text().toInt());
        ui->record->append("Me Say:" + ui->msg->toPlainText());
    });

//    read msg
    connect(udp1, &QUdpSocket::readyRead, this,[=](){
       qint64 size = udp1->pendingDatagramSize();
       QByteArray array(size,0);
       udp1->readDatagram(array.data(),size);
       ui->record->append(array);
    });
}

Server::~Server()
{
    delete ui;
}

